package com.lilosoft.core.utils;

import org.apache.commons.codec.binary.Base64;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;


public class TokenProcessor {

    private TokenProcessor() {}
    private static TokenProcessor instance = new TokenProcessor();
    
    public static TokenProcessor getInstance() {
    	return instance;
    }

    public String generateToken() {
    	String value = System.currentTimeMillis()+ new Random().nextInt() + "";
    	//
    	try{
    		MessageDigest md = MessageDigest.getInstance("md5");
    		byte[] b = md.digest(value.getBytes()); //产生数据的指纹


    		//BASE64Encoder,已经过期,不使用
    		//BASE64Encoder be = new BASE64Encoder();
    		//String token = be.encode(b);

			Base64 be =new Base64();
			String token = be.encodeAsString(b);
    		token = token.replaceAll("=", "").replaceAll("/", "").replaceAll("\\+", "");
    		return token;
    	} catch(NoSuchAlgorithmException e) {
    		e.printStackTrace();
    	}
    	
    	return null;
    }
    
    public static void main(String[] args) throws Exception {
    	System.out.println(TokenProcessor.getInstance().generateToken());
    	System.out.println(TokenProcessor.getInstance().generateToken());
    	System.out.println(TokenProcessor.getInstance().generateToken());
    	System.out.println(TokenProcessor.getInstance().generateToken());
    	System.out.println(TokenProcessor.getInstance().generateToken());
    }
}
